package com.ruoyi.web.controller.system.fuw.wx;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.LogUtils;
import com.ruoyi.fuw.domain.*;
import com.ruoyi.fuw.service.*;
import com.ruoyi.web.controller.util.DataUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Wx订单信息Controller
 *
 * @author zjh
 * @date 2021-10-09
 */
@RestController
@RequestMapping("/api/wx/order")
public class WxFuwOrderController extends BaseController {

    @Autowired
    private IFuwOrderService fuwOrderService;

    @Autowired
    private IFuwCommsOrdersService fuwCommsOrdersService;

    @Autowired
    private IFuwCommService fuwCommService;

    @Autowired
    private IFuwCarService fuwCarService;

    /**
     * 购物车商品购买
     */
    @PreAuthorize("@ss.hasPermi('fuw:car:buyComm')")
    @Log(title = "购物车", businessType = BusinessType.OTHER)
    @PostMapping(value = "/add/addOrder")
    public AjaxResult addOrderPay(@RequestParam("allMoney") BigDecimal allMoney,
                                  @RequestParam("carString") String carString,
                                  @RequestParam("numString") String numString)
    {
        System.out.println("allMoney =" + allMoney);
        System.out.println("carString =" + carString);
        System.out.println("numString =" + numString);

        /**
         * 新增订单信息
         */
        FuwOrder fuwOrder = new FuwOrder();
        // 自定义格式UI
        String uuidStr = DataUtils.fuwUUID("Odr");
        fuwOrder.setOrderId(uuidStr);
        // 用户编号
        fuwOrder.setPersonId(getUsername());
        // 总金额
        fuwOrder.setAllMoney(allMoney);
        // 生成订单信息时间
        fuwOrder.setOrderStartTime(DateUtils.parseDate(DateUtils.getTime()));
        // 给予订单状态 （1：待付款；2：代发货；3：待收货；4：待评价；5：退换货；6：订单异常）
        fuwOrder.setOrderType("1");
        // 新增订单信息
        fuwOrderService.insertFuwOrder(fuwOrder);
        LogUtils.getBlock("订单信息" + "新增成功！");

        /**
         * 新增商品订单信息
         */
        // 拆分字符串，获取商品信息和商品数量
        String[] carStrings = carString.split(","); // 商品信息
        // 将商品数量中的undefined替换为0
        numString = numString.replaceAll("undefined", "0");
        String[] numStrings = numString.split(","); // 商品数量
        // 循环遍历新增商品订单信息
        for(int i=0; i<carStrings.length; i++){

            if(Integer.valueOf(numStrings[i]) != 0){
                // 根据commId查询对应的商品信息
                FuwComm fuwComm = fuwCommService.selectFuwCommByCommId(carStrings[i]);
                // 新建商品订单信息
                FuwCommsOrders fuwCommsOrders = new FuwCommsOrders();
                fuwCommsOrders.setOrderId(uuidStr);
                fuwCommsOrders.setCommId(carStrings[i]);
                fuwCommsOrders.setCommNum(Long.valueOf(numStrings[i]));
                fuwCommsOrders.setCommDanjia(fuwComm.getCommDanjia());
                fuwCommsOrders.setCommZhekou(fuwComm.getCommZhekou());
                // 新增商品订单
                fuwCommsOrdersService.insertFuwCommsOrders(fuwCommsOrders);
                LogUtils.getBlock("商品订单信息" + "新增成功！");

                /**
                 * 修改购物车内的信息
                 */
                FuwCar fuwCar = new FuwCar();
                fuwCar.setPersonId(getUsername());
                fuwCar.setCommId(carStrings[i]);
                fuwCarService.deleteFuwCarByFuwCar(fuwCar);
                LogUtils.getBlock("购物车信息" + "修改成功！");

                /**
                 * 修改商品库存信息
                 */
                fuwComm.setCommKucun(fuwComm.getCommKucun() - Integer.valueOf(numStrings[i]));
                fuwCommService.updateFuwComm(fuwComm);
                LogUtils.getBlock("商品信息" + "修改成功！");
            }

        }

        return AjaxResult.success(fuwOrder);
    }

    /**
     * 修改订单信息
     */
    @PreAuthorize("@ss.hasPermi('fuw:order:edit')")
    @Log(title = "订单信息", businessType = BusinessType.UPDATE)
    @PostMapping(value = "/update/order")
    public AjaxResult edit(@RequestParam("orderId") String orderId)
    {
        // 查询订单信息
        FuwOrder fuwOrder = fuwOrderService.selectFuwOrderByOrderId(orderId);
        //修改订单信息变为付款
        fuwOrder.setOrderType("2");
        return toAjax(fuwOrderService.updateFuwOrder(fuwOrder));
    }

    /**
     * 查看当前用户全部订单信息
     */
    @PreAuthorize("@ss.hasPermi('fuw:order:details')")
    @Log(title = "订单详情", businessType = BusinessType.OTHER)
    @PostMapping(value = "/list")
    public AjaxResult details(@RequestParam("personId") String personId)
    {
        // 查询当前用户的订单信息
        FuwOrder fuwOrder = new FuwOrder();
        fuwOrder.setPersonId(personId);
        List<FuwOrder> fuwOrderList = fuwOrderService.selectFuwOrderList(fuwOrder);

        // list
        List<Map<String,Object>> listMap = new ArrayList<Map<String,Object>>();

        for(FuwOrder fuwOrderNow: fuwOrderList){
            // 在orders列表中查询该订单信息拥有的商品
            FuwCommsOrders fuwCommsOrders = new FuwCommsOrders();
            fuwCommsOrders.setOrderId(fuwOrderNow.getOrderId());
            List<FuwCommsOrders> fuwCommsOrdersList = fuwCommsOrdersService.selectFuwCommsOrdersList(fuwCommsOrders);

            // 遍历查询到的orders商品列表信息，去comm商品信息中获取详细的商品信息
            for(FuwCommsOrders fuwCommsOrdersNow: fuwCommsOrdersList){
                FuwComm fuwComm = fuwCommService.selectFuwCommByCommId(fuwCommsOrdersNow.getCommId());

                Map<String, Object> mapNew = new HashMap<>();

                // 存放基本信息
                mapNew.put("commId", fuwComm.getCommId());
                mapNew.put("commName", fuwComm.getCommName());
                mapNew.put("commPicture", fuwComm.getCommPicture());

                mapNew.put("num", fuwCommsOrdersNow.getCommNum());
                mapNew.put("commDanjia", fuwCommsOrdersNow.getCommDanjia());
                mapNew.put("commZheKou", fuwCommsOrdersNow.getCommZhekou());

                // 将分类优化显示
                String[] types = fuwComm.getCommType().split(",");
                String typeNew = "";
                for(int i=0; i<types.length; i++){
                    typeNew = typeNew + types[i];
                    if(i < types.length - 1){
                        typeNew = typeNew + " >>> ";
                    }
                }
                fuwComm.setCommType(typeNew);

                mapNew.put("orderId", fuwOrderNow.getOrderId());
                mapNew.put("allMoney", fuwOrderNow.getAllMoney());
                mapNew.put("orderStartTime", fuwOrderNow.getOrderStartTime());
                mapNew.put("orderType", fuwOrderNow.getOrderType());

                listMap.add(mapNew);
            }
        }

        return AjaxResult.success(listMap);
    }

}
